package other.xsy.paas;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.http.RkhdHttpData;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.trigger.DataResult;
import other.xsy.paas.utils.HCXObjectService;
import other.xsy.paas.utils.TfReturnMsgTools;

import java.io.IOException;

/**
 * 功能描述：自义定订单生效接口
 *
 * @author whz
 * @ClassName: OrderApi
 * @Description:
 * @date 2024年03月30日
 */
@RestApi(baseUrl = "/order")
public class OrderApi {

    private static final Logger logger = LoggerFactory.getLogger();
    private static HCXObjectService hcxObjectService = new HCXObjectService();

    public static void main(String[] args) {
        OrderApi test = new OrderApi();
        test.handler2(3232250834603307L);
    }

    @RestMapping(value = "/deactivation", method = RequestMethod.POST)
    public String deactivation(@RestQueryParam(name = "id") Long id) throws ApiEntityServiceException {
        logger.info("自义定订单失效接口,执行了按钮事件：" + id);
        return handler2(id);
    }

    private String handler2(Long id) {
        try {
            Order order = new Order();
            order.setId(id);
            order = hcxObjectService.get(order);
            order.setPoStatus(1);
            logger.info("订单编号：" + order.getPo());
            OrderUpdateTrigger orderUpdateTrigger = new OrderUpdateTrigger();
            DataResult dataResult = new DataResult();
            dataResult.setSuccess(true);
            orderUpdateTrigger.handler(order, dataResult);
            Boolean success = dataResult.getSuccess();
            if (!success) {
                return TfReturnMsgTools.getFailResult(dataResult.getMsg());
            }
            RkhdHttpClient instance = RkhdHttpClient.instance();
            RkhdHttpData patch = RkhdHttpData.newBuilder().callString("/rest/data/v2.0/xobjects/order/actions/deactivation?recordId=" + id)
                    .callType("PATCH").build();
            JSONObject execute = instance.execute(patch, JSONObject::parseObject);
            logger.info("调用生效接口结果：" + execute.toJSONString());
            Long code = execute.getLong("code");
            if (code == 200) {
                return TfReturnMsgTools.getSuccessResult("成功");
            }
            return TfReturnMsgTools.getFailResult(execute.getString("msg"));
        } catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
            return TfReturnMsgTools.getFailResult("失败");
        }
    }


    @RestMapping(value = "/takeEffect", method = RequestMethod.POST)
    public String takeEffect(@RestQueryParam(name = "id") Long id) throws ApiEntityServiceException {
        logger.info("自义定订单生效接口,执行了按钮事件：" + id);
        return handler(id);
    }

    private String handler(Long id) {
        try {
            RkhdHttpClient instance = RkhdHttpClient.instance();
            RkhdHttpData patch = RkhdHttpData.newBuilder().callString("/rest/data/v2.0/xobjects/order/actions/activation?recordId=" + id)
                    .callType("PATCH").build();
            JSONObject execute = instance.execute(patch, JSONObject::parseObject);
            logger.info("调用生效接口结果：" + execute.toJSONString());
            Long code = execute.getLong("code");
            if (code == 200) {
                pushOrderToPms(id);
                return TfReturnMsgTools.getSuccessResult("成功");
            }
            return TfReturnMsgTools.getFailResult(execute.getString("msg"));
        } catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
            return TfReturnMsgTools.getFailResult("失败");
        }
    }


    /**
     * 发送请求，调用自定义接口推送到PMS
     * @param orderId
     * @throws IOException
     * @throws XsyHttpException
     */
    public void pushOrderToPms(Long orderId) throws IOException, XsyHttpException {
        logger.info("生效订单后推送订单到PMS = " + orderId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", orderId);

        RkhdHttpData data = new RkhdHttpData();
        data.setCall_type("POST");
        data.setCallString("/rest/data/v2.0/scripts/api/pms/pushPmsOrderData?id=" + orderId);
        data.setBody(jsonObject.toJSONString());
        JSONObject result = RkhdHttpClient.instance().execute(data, JSONObject::parseObject);
        logger.debug("发送pass自定义请求：" + result);
        if (result.getInteger("code") != 0) {
            logger.error("推送订单数据到PMS: " + result.getString("msg"));
        }
    }
}
